import axios from 'axios'

// 自定义axios
const myaxios = axios.create({
  baseURL: 'http://106.15.41.34/api',
  timeout: 10000
})

// 拦截请求,携带token数据
myaxios.interceptors.request.use(function (config) {
  config.headers.token = localStorage.getItem('token')
  // console.log(config)
  return config
}, function (error) {
  // Do something with request error
  return Promise.reject(error)
})

// 拦截响应,登录守卫
myaxios.interceptors.response.use(function (response) {
  const url = response.config.url
  if (response.data.code === 400) {
    // console.log(response.config.url)
    // console.log('登录失效，需要重新登录')
    if (url.includes('cart')) {
      location.href = '#/login?to=/cart'
    } else if (url.includes('order')) {
      location.href = '#/login?to=/order'
    } else if (url.includes('user')) {
      location.href = '#/login?to=/my'
    } else if (url.includes('search')) {
      location.href = '#/login?to=/search'
    }
  }
  return response
}, function (error) {
  // Do something with response error
  return Promise.reject(error)
})

export default myaxios
